
// 主机数据存储


var hostData = [
    {
        id: 1,
        _selected: false,
        name: 'web-server-01',
        host: '192.168.1.100',
        port: 22,
        username: 'root',
        password: 'password123',
        private_key: '',
        passphrase: '',
        auth_type: 'password',
        timeout: 10,
        description: 'Web服务器主机',
        tags: 'web,nginx,production',
        status: '在线'
    },
    {
        id: 2,
        _selected: false,
        name: 'api-server-01',
        host: '192.168.1.101',
        port: 22,
        username: 'ubuntu',
        password: '',
        private_key: '~/.ssh/id_rsa',
        passphrase: '',
        auth_type: 'key',
        timeout: 10,
        description: 'API服务器',
        tags: 'api,nodejs,production',
        status: '在线'
    },
    {
        id: 3,
        _selected: false,
        name: 'db-server-01',
        host: '192.168.1.102',
        port: 22,
        username: 'admin',
        password: 'admin123',
        private_key: '~/.ssh/id_rsa',
        passphrase: 'keypass',
        auth_type: 'both',
        timeout: 15,
        description: '数据库服务器',
        tags: 'database,mysql,production',
        status: '离线'
    }
];

var hostTableIns = null;


layui.use(['table', 'layer', 'form', 'element'], function(){
        var table = layui.table,
            layer = layui.layer,
            form = layui.form,
            $ = layui.$,
            element = layui.element;


        // 当前操作状态
        var currentHostAction = '';
        var currentHostId = null;


        // 渲染主机表格
        function renderHostTable() {
            // console.log('开始渲染主机表格，数据：', hostData);
            hostData.sort(function(a, b) {
                return a.sort_order - b.sort_order;
            });

            hostTableIns = table.render({
                elem: '#hostTable',
                data: hostData,
                toolbar: '#hostToolbarDemo',
                defaultToolbar: ['filter', 'exports', 'print'],
                cols: [[ 
                    {type: 'checkbox', fixed: 'left'},
                    // {field: 'sort_order', title: '序号', width: 80, sort: true, templet: '#sortNumTpl'}, // 修改这里
                    {field: 'id', title: '序号', width: 80, sort: true, fixed: 'left',edit: 'text'},
                    {field: 'name', title: '主机名', width: 150, edit: 'text'},
                    {field: 'host', title: 'IP地址', width: 180, edit: 'text'},
                    {field: 'port', title: '端口', width: 80, edit: 'text'},
                    {field: 'username', title: '用户名', width: 100, edit: 'text'},
                    {field: 'password', title: '密码', width: 120, templet: '#passwordTpl'},
                    {field: 'private_key', title: '私钥路径', width: 150, edit: 'text'},
                    {field: 'auth_type', title: '认证方式', width: 100, templet: function(d){
                        var authMap = {
                            'password': '密码认证',
                            'key': '密钥认证',
                            'both': '密码+密钥'
                        };
                        return authMap[d.auth_type] || d.auth_type;
                    }},
                    {field: 'status', title: '状态', width: 80, templet: '#hostStatusTpl'},
                    {field: 'description', title: '描述', width: 150},
                    {title: '操作', toolbar: '#hostBarDemo', width: 250, fixed: 'right'}
                ]],
                skin: 'line',
                even: true,
                page: true,
                limits: [10, 15, 20, 25, 50, 100],
                limit: 15,
                loading: false,
                text: {
                    none: '暂无相关数据'
                }
            });
            console.log('主机表格渲染完成');
        }

        // 重新加载主机表格数据
        function reloadHostTable() {
            if (hostTableIns) {
                hostTableIns.reload({
                    data: hostData
                });
            }
        }

        // 根据ID获取主机数据
        function getHostById(id) {
            return hostData.find(function(host) {
                return host.id === id;
            });
        }

        // 主机搜索功能
        $('#hostSearchInput').on('input', function() {
            var searchTerm = $(this).val().toLowerCase();
            if (searchTerm === '') {
                reloadHostTable();
            } else {
                var filteredData = hostData.filter(function(host) {
                    return host.name.toLowerCase().includes(searchTerm) || 
                        host.host.toLowerCase().includes(searchTerm) ||
                        host.username.toLowerCase().includes(searchTerm) ||
                        host.description.toLowerCase().includes(searchTerm) ||
                        host.tags.toLowerCase().includes(searchTerm);
                });
                
                hostTableIns.reload({
                    data: filteredData
                });
            }
        });


        // 清空主机表单
        function clearHostForm() {
            // $('#host_config')[0].reset();
            $('select[name="auth_type"]').val('password');
            $('#password-field').show();
            $('#key-field').hide();
            $('#passphrase-field').hide();
            form.render();
        }

        // 填充主机表单数据
        function fillHostForm(hostData) {
            $('input[name="hostname"]').val(hostData.name);
            $('input[name="ip"]').val(hostData.host);
            $('input[name="port"]').val(hostData.port);
            $('input[name="username"]').val(hostData.username);
            $('input[name="password"]').val(hostData.password);
            $('input[name="private_key"]').val(hostData.private_key);
            $('input[name="passphrase"]').val(hostData.passphrase);
            $('select[name="auth_type"]').val(hostData.auth_type);
            $('input[name="timeout"]').val(hostData.timeout);
            $('textarea[name="description"]').val(hostData.description);
            $('input[name="tags"]').val(hostData.tags);

            // 根据认证方式显示相应字段
            updateAuthFields(hostData.auth_type);
            
            form.render();
        }

        // 更新认证字段显示
        function updateAuthFields(authType) {
            $('#password-field').hide();
            $('#key-field').hide();
            $('#passphrase-field').hide();
            
            switch(authType) {
                case 'password':
                    $('#password-field').show();
                    break;
                case 'key':
                    $('#key-field').show();
                    $('#passphrase-field').show();
                    break;
                case 'both':
                    $('#password-field').show();
                    $('#key-field').show();
                    $('#passphrase-field').show();
                    break;
            }
        }

        // 收集主机表单数据
        function collectHostFormData() {
            return {
                name: $('input[name="hostname"]').val(),
                host: $('input[name="ip"]').val(),
                port: parseInt($('input[name="port"]').val()) || 22,
                username: $('input[name="username"]').val(),
                password: $('input[name="password"]').val(),
                private_key: $('input[name="private_key"]').val(),
                passphrase: $('input[name="passphrase"]').val(),
                auth_type: $('select[name="auth_type"]').val(),
                timeout: parseInt($('input[name="timeout"]').val()) || 10,
                description: $('textarea[name="description"]').val(),
                tags: $('input[name="tags"]').val(),
                status: '未知'
            };
        }

        // 验证主机表单数据
        function validateHostForm(formData) {
            if (!formData.name) {
                layer.msg('请输入主机名', {icon: 2});
                return false;
            }
            if (!formData.host) {
                layer.msg('请输入IP地址', {icon: 2});
                return false;
            }
            if (!formData.username) {
                layer.msg('请输入用户名', {icon: 2});
                return false;
            }
            return true;
        }

        // 监听主机表格复选框选择事件
        table.on('checkbox(hostTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;

            for (let i = 0; i < hostData.length; i++) {
                hostData[i]._selected = false;
            }

            data.forEach(function(item) {
                var index = hostData.findIndex(function(host) {
                    return host.id === item.id;
                });
                if (index !== -1) {
                    hostData[index]._selected =true;
                }
            });
        });



        // 监听主机表格头工具栏事件
        table.on('toolbar(hostTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    currentHostAction = 'add';
                    currentHostId = null;
                    
                    layer.open({
                        type: 1,
                        title: '添加主机',
                        content: $('#hostFormModal'),
                        area: ['700px', '80%'],
                        maxmin: true,
                        success: function() {
                            clearHostForm();
                        }
                    });
                    break;
                case 'batchDelete':
                    var data = checkStatus.data;
                    if(data.length === 0){
                        layer.msg('请选择要删除的数据');
                    } else {
                        layer.confirm('确定删除选中的主机吗？', function(index){
                            data.forEach(function(item) {
                                hostData = hostData.filter(function(host) {
                                    return host.id !== item.id;
                                });
                            });
                            
                            reloadHostTable();
                            layer.close(index);
                            layer.msg('删除成功');
                        });
                    }
                    break;
            }
        });

        // 监听主机表格行工具事件
        table.on('tool(hostTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确定删除这个主机吗？', function(index){
                    hostData = hostData.filter(function(host) {
                        return host.id !== data.id;
                    });
                    reloadHostTable();
                    layer.close(index);
                    layer.msg('删除成功');
                });
            } else if(obj.event === 'edit'){
                currentHostAction = 'edit';
                currentHostId = data.id;
                var host = getHostById(currentHostId);
                
                layer.open({
                    type: 1,
                    title: '编辑主机',
                    content: $('#hostFormModal'),
                    area: ['700px', '80%'],
                    maxmin: true,
                    success: function() {
                        fillHostForm(host);
                    }
                });
            } else if(obj.event === 'detail'){
                layer.open({
                    type: 1,
                    title: '主机详情',
                    content: '<div style="padding: 20px;"><pre>' + generateHostYaml(data) + '</pre></div>',
                    area: ['600px', '500px']
                });
            } else if(obj.event === 'test'){
                layer.msg('正在测试连接...', {icon: 16, time: 2000});
                setTimeout(function() {
                    layer.msg('连接测试成功', {icon: 1});
                }, 2000);
            } else if(obj.event === 'showPassword'){
                layer.prompt({
                    title: '密码',
                    formType: 0,
                    value: data.password,
                    area: ['300px', '150px']
                }, function(value, index){
                    layer.close(index);
                });
            }
        });


         // 监听单元格编辑
        table.on('edit(hostTable)', function(obj){
            var value = obj.value,
                data = obj.data,
                field = obj.field;
            
            // 更新数据
            var index = hostData.findIndex(function(host) {
                return host.id === data.id;
            });
            
            if (index !== -1) {
                hostData[index][field] = value;
                layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
            }
        });


        // 外部主机按钮事件
        $('#addHost').on('click', function() {
            currentHostAction = 'add';
            currentHostId = null;
            
            layer.open({
                type: 1,
                title: '添加主机',
                content: $('#hostFormModal'),
                area: ['700px', '80%'],
                maxmin: true,
                success: function() {
                    clearHostForm();
                }
            });
        });

        $('#editHost').on('click', function() {
            var checkStatus = table.checkStatus('hostTable');
            var data = checkStatus.data;
            
            if (data.length === 0) {
                layer.msg('请选择要编辑的主机', {icon: 2});
                return;
            }
            
            if (data.length > 1) {
                layer.msg('只能选择一个主机进行编辑', {icon: 2});
                return;
            }
            
            currentHostAction = 'edit';
            currentHostId = data[0].id;
            var host = getHostById(currentHostId);
            
            layer.open({
                type: 1,
                title: '编辑主机',
                content: $('#hostFormModal'),
                area: ['700px', '80%'],
                maxmin: true,
                success: function() {
                    fillHostForm(host);
                }
            });
        });

        $('#deleteHost').on('click', function() {
            var checkStatus = table.checkStatus('hostTable');
            var data = checkStatus.data;
            
            if (data.length === 0) {
                layer.msg('请选择要删除的主机', {icon: 2});
                return;
            }
            
            layer.confirm('确定要删除选中的主机吗？', {icon: 3, title: '确认删除'}, function(index) {
                data.forEach(function(item) {
                    hostData = hostData.filter(function(host) {
                        return host.id !== item.id;
                    });
                });
                
                reloadHostTable();
                layer.close(index);
                layer.msg('删除成功', {icon: 1});
            });
        });

        // 认证方式选择事件
        form.on('select(authTypeSelect)', function(data){
            updateAuthFields(data.value);
        });

        // 主机表单提交按钮事件
        $(document).on('click', '#host-submit-btn', function() {
            var formData = collectHostFormData();
            
            if (!validateHostForm(formData)) {
                return;
            }
            
            if (currentHostAction === 'add') {
                var maxId = hostData.length > 0 ? Math.max.apply(Math, hostData.map(function(host) {
                    return host.id;
                })) : 0;
                formData.id = maxId + 1;
                
                hostData.push(formData);
                layer.msg('主机添加成功', {icon: 1});
            } else if (currentHostAction === 'edit') {
                formData.id = currentHostId;
                var index = hostData.findIndex(function(host) {
                    return host.id === currentHostId;
                });
                
                if (index !== -1) {
                    formData.status = hostData[index].status;
                    hostData[index] = formData;
                    layer.msg('主机修改成功', {icon: 1});
                }
            }
            
            reloadHostTable();
            layer.closeAll();
        });

        // 主机表单重置按钮事件
        $(document).on('click', '#host-reset-btn', function() {
            if (currentHostAction === 'edit') {
                var host = getHostById(currentHostId);
                fillHostForm(host);
            } else {
                clearHostForm();
            }
        });

        // 主机搜索功能
        $('#searchHostInput').on('input', function() {
            var searchTerm = $(this).val().toLowerCase();
            if (searchTerm === '') {
                reloadHostTable();
            } else {
                var filteredData = hostData.filter(function(host) {
                    return host.name.toLowerCase().includes(searchTerm) || 
                            host.host.toLowerCase().includes(searchTerm) ||
                            host.username.toLowerCase().includes(searchTerm) ||
                            (host.description && host.description.toLowerCase().includes(searchTerm)) ||
                            (host.tags && host.tags.toLowerCase().includes(searchTerm));
                });
                
                if (hostTableIns) {
                    hostTableIns.reload({
                        data: filteredData
                    });
                }
            }
        });

        // 导出主机配置功能
        $('#generateHostConfig').on('click', function() {
            var config = {
                hosts: hostData
            };
            
            var configJson = JSON.stringify(config, null, 2);
            
            layer.open({
                type: 1,
                title: '主机配置预览',
                content: '<div style="padding: 20px;"><pre style="max-height: 500px; overflow-y: auto;">' + configJson + '</pre></div>',
                area: ['800px', '600px'],
                btn: ['下载配置文件', '关闭'],
                yes: function(index) {
                    var blob = new Blob([configJson], {type: 'application/json'});
                    var url = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = 'host_config.json';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    layer.close(index);
                }
            });
        });

        // 初始化表格
        console.log('开始初始化表格');
        renderHostTable();
        console.log('表格初始化完成');
    });


    // json 转 yaml
function generateHostYaml(host) {
    var yaml = '';
    yaml += `  - name: "${host.name}"\n`;
    yaml += `    host: "${host.host}"\n`;
    yaml += `    username: "${host.username}"\n`;
    yaml += `    password: "${host.password}"\n`;
    yaml += `    port: ${host.port}\n`;
    yaml += `    timeout: ${host.timeout}\n`;
    // yaml += `    auth_type: "${host.auth_type}"\n`;
    // yaml += `    description: "${host.description}"\n`;
    // yaml += `    tags: "${host.tags}"\n\n`;
    return yaml;
}